package cn.com.gas.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasAnalyseRatioRingEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasAnalyseRatioRingService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 月销环比分析
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-04-15 20:42:03
 */
@Controller
@RequestMapping("/gas/analyse/ratioring")
public class GasAnalyseRatioRingController {
	@Autowired
	private GasAnalyseRatioRingService gasAnalyseRatioRingService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private HttpSessionService httpSessionService;
	@Autowired
	private DeptService deptService;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/list")
	// @RequiresPermissions("gasAnalyseRatioRing:list")
	@ResponseBody
	public DataResult findListByPage(@RequestBody GasAnalyseRatioRingEntity gasAnalyseRatioRing) {
		String currentDeptId = httpSessionService.getCurrentDeptId();

		List<String> stationIdList = new ArrayList<>();
		LambdaQueryWrapper<GasStationinfoEntity> stationinfoQueryWrapper = Wrappers.lambdaQuery();
		// stationinfoQueryWrapper.eq(GasStationinfoEntity::getPid,
		// "5c8baa4b-081f-41aa-a549-2235b786c7c7");
		// stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
		// stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

		// LambdaQueryWrapper<GasStationinfoEntity> queryWrapperStationinfo =
		// Wrappers.lambdaQuery();

		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 市局
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			stationinfoQueryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
		} else {
			// 省局
		}

		List<GasStationinfoEntity> stationinfoList = gasStationinfoService.list(stationinfoQueryWrapper);

		for (GasStationinfoEntity gasStationinfoEntity : stationinfoList) {
			stationIdList.add(gasStationinfoEntity.getId());

		}

		Page page = new Page(gasAnalyseRatioRing.getPage(), gasAnalyseRatioRing.getLimit());
		LambdaQueryWrapper<GasAnalyseRatioRingEntity> queryWrapper = Wrappers.lambdaQuery();

		if (TsBqUtils.isNotNull(gasAnalyseRatioRing.getStationName())) {
			queryWrapper.like(GasAnalyseRatioRingEntity::getStationName, gasAnalyseRatioRing.getStationName());
		}

		if (TsBqUtils.isNotNull(gasAnalyseRatioRing.getYearMonths())) {
			queryWrapper.eq(GasAnalyseRatioRingEntity::getYearMonths, gasAnalyseRatioRing.getYearMonths());
		}
		queryWrapper.in(GasAnalyseRatioRingEntity::getStationId, stationIdList);

		IPage<GasAnalyseRatioRingEntity> iPage = gasAnalyseRatioRingService.page(page, queryWrapper);
		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据（税务机关）")
	@PostMapping("/list1")
	@ResponseBody
	public DataResult list1(@RequestBody GasAnalyseRatioRingEntity gasAnalyseRatioRing) {
		String yearMonths = gasAnalyseRatioRing.getYearMonths();
		if (TsBqUtils.isNull(yearMonths)) {
			return DataResult.fail("月份不能为空！");
		}

		String currentDeptId = httpSessionService.getCurrentDeptId();

		Page page = new Page(gasAnalyseRatioRing.getPage(), gasAnalyseRatioRing.getLimit());
		LambdaQueryWrapper<SysDept> deptQueryWrapper = Wrappers.lambdaQuery();
		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			deptQueryWrapper.eq(SysDept::getId, currentDeptId);
		} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 市局
			deptQueryWrapper.like(SysDept::getId, currentDeptId.substring(0, 5));
		}

		IPage<SysDept> iPage = deptService.page(page, deptQueryWrapper);
		List<SysDept> records = iPage.getRecords();
		for (SysDept dept : records) {
			String deptId = dept.getId();

			LambdaQueryWrapper<GasAnalyseRatioRingEntity> analyseRatioWrapper = Wrappers.lambdaQuery();

			if (TsBqUtils.isNotNull(yearMonths)) {
				analyseRatioWrapper.eq(GasAnalyseRatioRingEntity::getYearMonths, yearMonths);
			}
			
			
			if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(deptId))) {
				// 县区局
				analyseRatioWrapper.eq(GasAnalyseRatioRingEntity::getTaxorgcode, deptId);
			} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(deptId))) {
				// 市局
				analyseRatioWrapper.like(GasAnalyseRatioRingEntity::getTaxorgcode, deptId.substring(0, 5));
			}else{
				// 省局
				
			}
			
			
			List<GasAnalyseRatioRingEntity> list = gasAnalyseRatioRingService.list(analyseRatioWrapper);

			if (TsBqUtils.isNotNull(list)) {

				// 计算销售、同比销售、同比 等平均值

				// 销售值
				double averageSale = list.stream().mapToDouble(GasAnalyseRatioRingEntity::getSaleAsDouble).sum();

				// 比较销售值
				double averageUpSale = list.stream().mapToDouble(GasAnalyseRatioRingEntity::getUpSaleAsDouble).sum();

				String averageSaleStr = Double.toString(averageSale);
				String averageUpSaleStr = Double.toString(averageUpSale);
				String ratioRingSale = getRatioRing(averageUpSaleStr, averageSaleStr);

				// 销售笔数
				int averageSaleAmount = (int)list.stream().mapToInt(GasAnalyseRatioRingEntity::getSaleAmountAsInt).sum();

				// 比较销售笔数
				int averageUpSaleAmount = (int)list.stream().mapToInt(GasAnalyseRatioRingEntity::getUpSaleAmountAsInt)
						.sum();

				String averageSaleAmountStr = averageSaleAmount + "";
				String averageUpSaleAmountStr = averageUpSaleAmount + "";
				String ratioRingSaleAmount = getRatioRing(averageUpSaleAmountStr,averageSaleAmountStr);
				
				BigDecimal averageSaleBd = new BigDecimal(averageSaleStr);
				BigDecimal averageUpSaleBd = new BigDecimal(averageUpSaleStr);
				
				dept.setAverageSale(String.valueOf(averageSaleBd.setScale(2, BigDecimal.ROUND_HALF_UP)));
				dept.setAverageUpSale(String.valueOf(averageUpSaleBd.setScale(2, BigDecimal.ROUND_HALF_UP)));
								dept.setRatioRingSale(ratioRingSale);

				dept.setAverageSaleAmount(averageSaleAmountStr);
				dept.setAverageUpSaleAsAmount(averageUpSaleAmountStr);
				dept.setRatioRingSaleAmount(ratioRingSaleAmount);

				dept.setYearMonths(yearMonths);

			}

		}

		return DataResult.success(iPage);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据（油站）")
	@PostMapping("/list2")
	@ResponseBody
	public DataResult list2(@RequestBody GasAnalyseRatioRingEntity gasAnalyseRatioRing) {

		String taxorgcode = gasAnalyseRatioRing.getTaxorgcode();
		String yearMonths = gasAnalyseRatioRing.getYearMonths();
		if (TsBqUtils.isNull(taxorgcode)) {
			return DataResult.fail("taxorgcode不能为空！");
		}

		if (TsBqUtils.isNull(yearMonths)) {
			return DataResult.fail("yearMonths不能为空！");
		}

		Page page = new Page(gasAnalyseRatioRing.getPage(), gasAnalyseRatioRing.getLimit());
		LambdaQueryWrapper<GasAnalyseRatioRingEntity> queryWrapper = Wrappers.lambdaQuery();
		
		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(taxorgcode))) {
			// 县区局
			queryWrapper.eq(GasAnalyseRatioRingEntity::getTaxorgcode, taxorgcode);
		} else if (Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(taxorgcode))) {
			// 市局
			queryWrapper.like(GasAnalyseRatioRingEntity::getTaxorgcode, taxorgcode.substring(0, 5));
		}
		

		queryWrapper.eq(GasAnalyseRatioRingEntity::getYearMonths, yearMonths);

		IPage<GasAnalyseRatioRingEntity> iPage = gasAnalyseRatioRingService.page(page, queryWrapper);
		return DataResult.success(iPage);
		
	}

	private static String getRatioRing(String upSale, String sale) {
		if (upSale.equals("0") || sale.equals("0") || upSale.equals("0.0") || sale.equals("0.0")) {
			return "0";
		}

		// 环比增长率计算公式为环比增长率=（本期数－上期数）/上期数×100%
		BigDecimal _upSale = new BigDecimal(upSale);
		BigDecimal _sale = new BigDecimal(sale);
		BigDecimal result = (_sale.subtract(_upSale)).divide(_upSale, 2, BigDecimal.ROUND_HALF_UP);

		return result.multiply(new BigDecimal(100)).toString() + "%";
	}

}
